package com.generation.builder;

import com.generation.Bean.Constants;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.Map;
import java.util.Properties;

/**
 * @author mockingjay
 * @date 2023/4/27 - 14:45
 */
public class BuildApplication {
    private static final Logger LOGGER = LoggerFactory.getLogger(BuildApplication.class);

    public static void excute(){

        File folder = new File(Constants.PATH_APPLICATION);
        if (!folder.exists()) {
            folder.mkdirs();
        }
        File File = new File(folder, "application" + ".yml");

        OutputStream out = null;
        OutputStreamWriter ow = null;
        BufferedWriter bw = null;
        try {
            out = new FileOutputStream(File);
            ow = new OutputStreamWriter(out, "utf8");
            bw = new BufferedWriter(ow);
            //配置velocity资源加载器
            Properties prop = new Properties();
            prop.put("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
            Velocity.init(prop);
            //封装mapper模板数据
            Map<String,Object> applicationTemplateData=Constants.TEMPLATE_APPLICATION_CONFIG_DATA;
            VelocityContext context = new VelocityContext(applicationTemplateData);
            String templatePath= Constants.TEMPLATE_APPLICATION_CONFIG;
            Template tpl = Velocity.getTemplate(templatePath, "UTF-8");
            tpl.merge(context, bw);
        } catch (Exception e) {
            LOGGER.error("创建application.yml失败", e);
        } finally {
            if (bw != null) {
                try {
                    bw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (ow != null) {
                try {
                    ow.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


    }
}
